package com.bs.util;

import org.springframework.web.cors.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 说明：
 * <p>
 * cors 跨域工具类
 *
 * @author 陈晓琪dellNotebook
 * @since 2025年05月11日 星期日 15:41:04
 */
public class CorsUtil {
    private static UrlBasedCorsConfigurationSource configSource;
    private static CorsProcessor processor = new DefaultCorsProcessor();

    static {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        config.addAllowedHeader("*");
        configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
    }

    /**
     * 为请求添加允许跨域响应头
     *
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException io异常
     */
    public static void addCors(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (CorsUtils.isCorsRequest(request)) {
            CorsConfiguration corsConfiguration = configSource.getCorsConfiguration(request);
            if (corsConfiguration != null) {
                boolean isValid = processor.processRequest(corsConfiguration, request, response);
                if (!isValid || CorsUtils.isPreFlightRequest(request)) {
                    return;
                }
            }
        }
    }
}
